<template>
  <div class="app-container">
    <el-row :gutter="24" class="mb8">
      <el-col :span="4">
        <el-menu :default-active="activeMenuIndex" id="menu" mode="vertical"
                 @open="handleMenuOpen"
                 @select="handleDbSel"
        >
          <SubMenu
            v-for="(firstItem, firstIndex) in firstLevelMenu"
            :key="firstIndex"
            :item="firstItem"
            :index="String(firstIndex)"
            :level="1"
            children="submenu"
            nameValue="name"
          />
        </el-menu>
        <div class="line"></div>
      </el-col>
      <el-col :span="20">
        <!--        搜索表单-->
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="88px">
          <el-form-item label="关键词" prop="keyword">
            <el-input v-model="queryParams.keyword" placeholder="请输入关键词" clearable
                      @keyup.enter.native="handleQuery"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <!--        顶部的修改，删除按钮-->
<!--        <el-row :gutter="10" class="mb8">-->
<!--          <el-col :span="1.5">-->
<!--            <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"-->
<!--                       v-hasPermi="['datasourceBase:edit']"-->
<!--            >修改-->
<!--            </el-button>-->
<!--          </el-col>-->
<!--          <el-col :span="1.5">-->
<!--            <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"-->
<!--                       v-hasPermi="['datasourceBase:remove']"-->
<!--            >删除-->
<!--            </el-button>-->
<!--          </el-col>-->
<!--          <right-toolbar @queryTable="getList"></right-toolbar>-->
<!--        </el-row>-->
        <!--        表格-->
        <el-table v-loading="loading" :data="tableList" @selection-change="handleSelectionChange">
<!--          <el-table-column type="selection" width="55" align="center" />-->
          <el-table-column type="index" width="50" align="center" label="序号"></el-table-column>
          <el-table-column label="子资源名" align="center" prop="tableName" width="180" />
          <el-table-column label="子资源别名" align="center" prop="tableNickName" width="180" />
          <el-table-column label="所在资源" align="center" prop="datasourceDbName" :show-overflow-tooltip="true" />
          <el-table-column label="记录数量" align="center" prop="quantity" >
            <template slot-scope="scope">
              {{ scope.row.quantity===null?'/': scope.row.quantity}}
           </template>
          </el-table-column>
          <el-table-column label="是否启用" align="center" prop="isUsing">
            <template slot-scope="scope">
              {{ scope.row.isUsing === 1 ? '是' : '否' }}
            </template>
          </el-table-column>

          <el-table-column label="是否共享" align="center" prop="isShare">
            <template slot-scope="scope">
              {{ scope.row.isShare === 1 ? '是' : '否' }}
            </template>
          </el-table-column>

          <el-table-column label="是否免费" align="center" prop="isFree">
            <template slot-scope="scope">
              {{ scope.row.isFree === 1 ? '是' : '否' }}
            </template>
          </el-table-column>
<!--          <el-table-column label="详细信息" align="center" prop="remark" />-->
          <el-table-column label="备注" align="center" prop="remark" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="200">
            <template slot-scope="scope">
<!--              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"-->
<!--                         v-hasPermi="['datasourceBase:edit']"-->
<!--              >修改-->
<!--              </el-button>-->
<!--              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"-->
<!--                         v-hasPermi="['datasourceBase:remove']"-->
<!--              >删除-->
<!--              </el-button>-->
              <el-button size="mini" type="text" icon="el-icon-more" @click="handleDetail(scope.row)"
                         v-hasPermi="['datasourceBase:remove']"
              >详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="tableTotal>0" :total="tableTotal" :page.sync="queryParams.currPage"
                    :limit.sync="queryParams.pageSize" @pagination="getList"
        />
        <!--    修改弹窗-->
        <el-dialog :title="UpdateTitle" :visible.sync="UpdateOpen" width="1200px" append-to-body>
        <div class="filed">
          <el-form :model="tableForm" label-width="120px"
                   ref="tableForm" :disabled="tableFormDisable">
            <el-row :gutter="10" class="mb8">
              <el-col :span="12">
                <el-form-item label="子资源名称" prop="tableName" required>
                  <el-input placeholder="请输入子资源名称" v-model="tableForm.tableName" disabled></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="子资源别名" prop="tableNickName" >
                  <el-input placeholder="请输入子资源别名" v-model="tableForm.tableNickName"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10" class="mb8">
              <el-col :span="12">
                <el-form-item label="所在数据库" prop="datasourceDbName" required>
                  <el-input placeholder="请输入数据库" v-model="tableForm.datasourceDbName" disabled></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="记录数量" prop="quantity" required>
                  <el-input placeholder="记录数量" v-model="tableForm.quantity" disabled></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10" class="mb8">
              <el-col :span="8">
                <el-form-item label="是否启用" prop="isUsing" required>
                  <el-radio v-model="tableForm.isUsing" :label=1>启用</el-radio>
                  <el-radio v-model="tableForm.isUsing" :label=0>不启用</el-radio>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="是否无条件共享" prop="isShare" required>
                  <el-radio v-model="tableForm.isShare" :label=1>是</el-radio>
                  <el-radio v-model="tableForm.isShare" :label=0>否</el-radio>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="是否免费" prop="isFree" required>
                  <el-radio v-model="tableForm.isFree" :label=1 >是</el-radio>
                  <el-radio v-model="tableForm.isFree" :label=0>否</el-radio>
                </el-form-item>
              </el-col>
            </el-row>
            <!--            <el-form-item label="前导库" prop="preDB" >-->
            <!--              <el-select-->
            <!--                v-model="value"-->
            <!--                multiple-->
            <!--                filterable-->
            <!--                remote-->
            <!--                reserve-keyword-->
            <!--                placeholder="请输入关键词"-->
            <!--                :remote-method="remoteMethod"-->
            <!--                :loading="dbLoading">-->
            <!--                <el-option-->
            <!--                  v-for="item in options"-->
            <!--                  :key="item.value"-->
            <!--                  :label="item.label"-->
            <!--                  :value="item.value">-->
            <!--                </el-option>-->
            <!--              </el-select>-->
            <!--            </el-form-item>-->


            <el-form-item label="备注" prop="remark" >
              <el-input v-model="tableForm.remark" placeholder="请输入平台详细介绍" type="textarea" maxlength="1000"
                        show-word-limit
              />
            </el-form-item>
            <el-row>
              <el-form-item label="子资源字段信息" prop="datasourceFieldVoList" required>
                <el-table :data="tableForm.datasourceFieldVoList">
                  <el-table-column type="index" width="50" align="center" label="序号"></el-table-column>
                  <el-table-column label="字段名称" align="center" prop="columnName" width="180" />
                  <el-table-column label="字段别名" align="center" width="180">
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.columnNickName"></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column label="字段类型" align="center" prop="columnType" width="180" />
                  <el-table-column label="是否丢弃" align="center" width="180">
                    <template slot-scope="scope">
                      <el-radio-group v-model="scope.row.isUsing">
                        <el-radio label=1>是</el-radio>
                        <el-radio label=0>否</el-radio>
                      </el-radio-group>
                    </template>
                  </el-table-column>
                </el-table>
                <!--                <pagination v-show="datasourceFieldVoTotal>0" :total="datasourceFieldVoTotal" :page.sync="queryParams.currPage"-->
                <!--                            :limit.sync="queryParams.pageSize" @pagination="getFileVoList"-->
                <!--                />-->
              </el-form-item>
            </el-row>
          </el-form>
        </div>
          <div slot="footer" class="dialog-footer" prop="status">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-dialog>
      </el-col>
    </el-row>
  </div>
</template>
<script>

import { platformAllByUnit, tableDel, tableList, tableUpdate, unitAll } from '@/api/qysj/app/rawData/table'
import { platformList } from '@/api/qysj/app/rawData/platformSystem'
import MenuNode from '@/views/qysj/data/source/MultiLevelMenu.vue'
import SubMenu from '@/views/qysj/data/raw/SubMenu.vue'
import { mapState } from 'vuex'
import { databaseAllByPlatform } from '@/api/qysj/app/rawData/Database'

export default {
  name: 'Table',
  components: { SubMenu, MenuNode },
  data() {
    return {
      // 查询参数
      queryParams: {
        keyword: '',
        pageSize: 10,
        currPage: 1,
        datasourceDbId:null
      },
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 加载表格
      loading: false,
      // 平台列表
      tableList: [],
      // 平台总数
      tableTotal: 0,
      // 新增表单标题
      UpdateTitle: '',
      // 弹出框状态
      UpdateOpen: false,
      // 平台信息表单
      tableForm: {},
      // 多选框相关
      options: [],
      value: [],
      list: [],
      dbLoading: false,
      // 目录
      activeMenuIndex: '1',
      // 目录列表
      firstLevelMenu: [],
      // 数据库字段列表
      fieldList: [],
      selIds: [],
      // 表单禁用
      tableFormDisable:false,
      // 当前目录层级
      // currentLevel:0,
      // 字段总数
      // datasourceFieldVoTotal:0,
    }

  },
  computed: {
    ...mapState('raw', ['currentLevel']) // 'raw' 对应你的模块名称，['level'] 是你要映射的状态名称
  },
  // watch: {
  //   // 监听子组件的 level 变化
  //   'submenuComponent.level'(newLevel) {
  //     console.log("New Level in Parent Component:", newLevel);
  //     // 执行其他逻辑
  //   },
  // },
  created() {
    this.getList()
    this.getUnitList();
    this.startTimer()
  },
  methods: {
    // 开始定时器
    startTimer() {
      this.timerId = setInterval(() => {
        // 在这里执行定时要执行的操作，例如重新加载数据
        this.getList();
      }, 3*60*1000); //三分钟定时刷新一次
    },
    // 停止定时器
    stopTimer() {
      clearInterval(this.timerId);
    },
    // 获取所有单位
    getUnitList(){
      unitAll().then(res=>{
        if (res.code===200){
          this.firstLevelMenu=res.data.map(item=>{
            return {
              name:item.unit,
              submenu:[]
            }
          });
        }else {
          this.$message(res.msg)
        }
      })
    },
    // 获取列表
    getList() {
      this.loading=true;
      tableList(this.queryParams).then(res => {
        if (res.code === 200) {
          this.tableList = res.rows
          this.tableTotal = res.total
          this.loading=false;
        } else {
          this.$message(res.msg)
        }
      })
    },
    // 多选框处理
    handleSelectionChange(selection) {
      this.selIds = selection.map((item) => item.id)
      // console.log('selItems', this.selIds,this.selIds.join(','))
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    handleMenuOpen(index) {
      const arr = index.split('-').map(Number);
      if (arr.length===1){
        const unitName=this.firstLevelMenu[arr[0]].name
        platformAllByUnit(unitName).then(res=>{
          if (res.code===200){
            // this.firstLevelMenu[parseInt(index)].submenu=res.data.map(item=>{
            //   return {
            //     name:item.systemName
            //   }
            // });
            this.$set(this.firstLevelMenu, index, {
              ...this.firstLevelMenu[index],
              submenu: res.data.map(item => {
                return {
                  id:item.id,
                  name: item.systemName,
                  submenu:[]
                };
              })
            });

            console.log('this.firstLevelMenu', this.firstLevelMenu)

            // console.log('this.firstLevelMenu', this.firstLevelMenu)
            this.$forceUpdate(); // 强制重新渲染组件
          }
        })
      }else if (arr.length===2){
        const secMenu=this.firstLevelMenu[arr[0]].submenu[arr[1]]
        const id=secMenu.id;
        databaseAllByPlatform(id).then(res=>{
          if (res.code===200){
           if (res.data){
             this.$set(this.firstLevelMenu[arr[0]].submenu, arr[1], {
               ...this.firstLevelMenu[arr[0]].submenu[arr[1]],
               submenu: res.data.map(item => {
                 return {
                   id:item.id,
                   name: item.dbName,
                 };
               })
             });
           }else {
             this.$message(res.msg)
           }
          }else {
            this.$message(res.msg)
          }
        })
      }

    },
    handleDbSel(index){
      const arr = index.split('-').map(Number);
      const id=this.firstLevelMenu[arr[0]].submenu[arr[1]].submenu[arr[2]].id;
      console.log('id', id)
      console.log('index', index)
      this.queryParams.datasourceDbId=id;
      this.getList()
      // tableList({datasourceDbId:id}).then(res=>{
      //   if (res.code===200){
      //     this.tableList=res.rows;
      //   }else {
      //     this.$message(res.msg)
      //   }
      // })
    },
    // 搜索按钮
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 重置按钮
    resetQuery() {
      this.resetForm('queryForm')//全局方法
      this.handleQuery()
    },
    // //新增按钮
    // handleAdd() {
    //   this.UpdateOpen = true
    //   this.UpdateTitle = '新增数据库信息'
    // },
    // 修改按钮
    handleUpdate(data) {
      this.UpdateOpen = true
      this.UpdateTitle = '修改子资源信息'
      this.tableForm=data
      // this.tableForm.isUsing=data.isUsing.toString()
      // this.tableForm.isShare=data.isShare.toString()
      // this.tableForm.isFree=data.isFree.toString()
      this.tableForm.datasourceFieldVoList = this.tableForm.datasourceFieldVoList.map(item => {
        item.isUsing = item.isUsing.toString(); // 将isUsing字段转换为字符串类型
        return item; // 返回修改后的对象
      });

    },
    // 删除按钮
    handleDelete(data) {
      const ids=data.id||this.selIds.join(',')
      tableDel(ids).then(res=>{
        if (res.code===200){
          this.$message('删除成功')
          this.getList()
        }else {
          this.$message(res.msg)
        }
      })
    },
    handleDetail(data) {
      this.tableFormDisable=true;
      this.UpdateOpen = true
      this.UpdateTitle = '子资源详细信息'
      this.tableForm=data
      this.tableForm.isUsing=data.isUsing.toString()
      this.tableForm.isShare=data.isShare.toString()
      this.tableForm.datasourceFieldVoList =
        this.tableForm.datasourceFieldVoList.map(item => {
        item.isUsing = item.isUsing.toString(); // 将isUsing字段转换为字符串类型
        return item; // 返回修改后的对象
      });
    },
    // 弹出框提交按钮
    submitForm() {
      this.tableForm.isUsing=parseInt(this.tableForm.isUsing)
      this.tableForm.isShare=parseInt(this.tableForm.isShare)
      this.tableForm.isFree=parseInt(this.tableForm.isFree)
      this.tableForm.datasourceFieldFormList=this.tableForm.datasourceFieldVoList;
      delete this.tableForm.datasourceFieldVoList;
      tableUpdate(JSON.stringify(this.tableForm)).then(res=>{
        if (res.code===200){
          this.$message("修改成功")
          this.UpdateOpen=false;
          this.$refs['tableForm'].resetFields()
        }else
        {
          this.$message(res.msg)
        }
      })
    },
    // 弹出框取消
    cancel() {
      this.$refs['tableForm'].resetFields()
    },

  },
  beforeDestroy() {
    // 在组件销毁前，停止定时器以防止内存泄漏
    this.stopTimer();
  },
}

</script>
<style >
#menu li.el-menu-item {
  margin-left: 50px;
}
/* 添加垂直滚动条 */
#menu {
  overflow-y: scroll; /* 或者 overflow-y: auto; */
  height: 858px; /* 设置容器的高度，以确定滚动条何时出现 */
}
/* 隐藏浏览器默认的滚动条 */
#menu::-webkit-scrollbar {
  width: 10px; /* 设置滚动条的宽度 */
}

/* 滚动条轨道 */
#menu::-webkit-scrollbar-track {
  background: #f1f1f1; /* 设置滚动条轨道的背景色 */
}

/* 滚动条滑块 */
#menu::-webkit-scrollbar-thumb {
  background: #888; /* 设置滚动条滑块的背景色 */
  border-radius: 5px; /* 设置滚动条滑块的圆角 */
}

/* 鼠标悬停在滑块上的样式 */
#menu::-webkit-scrollbar-thumb:hover {
  background: #555; /* 设置滚动条滑块悬停时的背景色 */
}
.filed {
  overflow-y: auto;
  max-height: 500px;
  overflow-x: hidden; /* 添加这一行以隐藏横向滚动条 */
}

.filed::-webkit-scrollbar {
  width: 10px; /* 调整滚动条宽度 */
}

.filed::-webkit-scrollbar-track {
  background: #f1f1f1; /* 滚动条背景颜色 */
}

.filed::-webkit-scrollbar-thumb {
  background: #888; /* 滚动条滑块颜色 */
  border-radius: 5px; /* 滚动条滑块圆角 */
}

.filed::-webkit-scrollbar-thumb:hover {
  background: #555; /* 鼠标悬停时滑块颜色 */
}


</style>
